package com.our.base.easylog.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import com.our.base.easylog.config.EasyLogProperties;

import lombok.Data;

/**
 * @author wuyang
 * @Description spring 的工具类
 * @date 2023/12/8
 **/
@Data
public class SpringUtils {

    private static final String PREFIX = "easy-log.";
    private static int status = -1;

    public static void startSpring() {
        status = 1;
    }

    public static void failedSpring() {
        status = 0;
    }

    public static int getSpringStatus() {
        return status;
    }

    /**
     * 从spring环境中读取配置信息并且赋值到EasyLogProperties中为空将为默认值，
     * 此方法只针对主配置easy-log下面的。
     * 二级配置读取不到。
     *
     * @param configurableApplicationContext spring配置信息
     * @return EasyLogProperties
     */
    public static EasyLogProperties getEasyLogConfig(ConfigurableApplicationContext configurableApplicationContext) {
        EasyLogProperties easyLogProperties = new EasyLogProperties();
        ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
        //根据反射拿到属性名，然后在通过以下方法根据属性名获取配置，如果不为空就赋值
        Field[] fields = easyLogProperties.getClass().getDeclaredFields();

        for (Field field : fields) {

            Object property = environment.getProperty(PREFIX + field.getName(), field.getType());
            try {
                if (property != null) {
                    field.setAccessible(true);
                    field.set(easyLogProperties, property);
                }

            } catch (IllegalAccessException ignored) {

            }


        }
        return easyLogProperties;


    }


    /**
     * 根据对应的类反射获取他的属性名
     *
     * @param tClass 传递的类
     * @return 属性名数组
     */
    private static List<String> getClassFieldNames(Class<?> tClass) {
        List<String> fieldsNameList = new ArrayList<>();
        Field[] fields = tClass.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            fieldsNameList.add(name);

        }
        return fieldsNameList;

    }

}
